package com.terrace.controller.quartz;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.terrace.core.common.model.ResultData;
import com.terrace.db.quartz.mapper.entity.SchedulerJob;
import com.terrace.db.quartz.service.QuartzService;
import com.terrace.core.mybatis.entity.Pagination;
import com.terrace.core.utils.validation.ValidationHelper;
import com.terrace.web.annotation.Logs;
import com.terrace.web.constant.GlobalsConstant;
import com.terrace.web.model.DataGrid;

@Controller
@Scope("prototype")
@RequestMapping("/quartz")
public class QuartzController {
	
	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(QuartzController.class);
	
	private static final String MESSAGE_TYPE = "调度任务";
	
	@Autowired
	private QuartzService quartzService;
	
	/**
	 * 默认管理页面
	 * @param request
	 * @return
	 */
	@RequestMapping
	public ModelAndView quartz(HttpServletRequest request){
		return new ModelAndView("system/quartz/quartzList");
	}
	
	/**
	 * 数据表格
	 * @param request
	 * @param pagination
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "datagrid")
	@RequiresPermissions("system:quartz:view")
	public DataGrid<SchedulerJob> datagrid(SchedulerJob job, Pagination<SchedulerJob> pagination, HttpServletRequest request) {
		DataGrid<SchedulerJob> dataGrid = new DataGrid<SchedulerJob>();
		dataGrid.setPagination(quartzService.selectSchedulerJobForPagination(pagination, job));
		return dataGrid;
	}
	
	/**
	 * 新增或者修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(@RequestParam(value = "schedName", required = false) String schedName,
			@RequestParam(value = "jobName", required = false) String jobName,
			@RequestParam(value = "jobGroup", required = false) String jobGroup,
			HttpServletRequest request) {
		if (StringUtils.isNotBlank(schedName) && StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(jobGroup)) {
			SchedulerJob job = quartzService.selectSchedulerJobByPrimaryKey(schedName, jobName, jobGroup);
			request.setAttribute("quartz", job);
		}
		return new ModelAndView("system/quartz/quartz");
	}
	
	/**
	 * 保存作业
	 * @param icon
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "saveOrUpdate")
	@RequiresPermissions("system:quartz:save")
	@Logs(depict = "调度任务保存", type = GlobalsConstant.LogTypes.SYS_SCHEDULER_JOB)
	public ResultData saveOrUpdate(SchedulerJob job, HttpServletRequest request) {
		ResultData rd = new ResultData();
		try {
			ValidationHelper helper = ValidationHelper.valid(job);
			if (helper.hasError()) {
				rd.setResult(helper.getErrors());
				return rd.failObjs("13105");
			}
			if (quartzService.checkSchedulerExists(job)) {
				rd.successObjs("10002", MESSAGE_TYPE);
				quartzService.updateSchedulerJob(job);
			} else {
				rd.successObjs("10001", MESSAGE_TYPE);
				quartzService.addSchedulerJob(job);
			}
		} catch (Exception e) {
			rd.failObjs("13101", MESSAGE_TYPE);
			logger.error(rd.getMessage() + "：", e);
		}
		return rd;
	}
	
	/**
	 * 删除作业
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "delete")
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequiresPermissions("system:quartz:delete")
	@Logs(depict = "删除调度任务", type = GlobalsConstant.LogTypes.SYS_SCHEDULER_JOB)
	public ResultData delete(SchedulerJob job, HttpServletRequest request) {
		ResultData rd = new ResultData();
		try {
			rd.successObjs("10003", MESSAGE_TYPE);
			quartzService.deleteSchedulerJob(job);
		} catch (Exception e) {
			rd.failObjs("13102", MESSAGE_TYPE);
			logger.error(rd.getMessage() + "：", e);
		}
		return rd;
	}
	
	/**
	 * 暂停调度任务
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "pause")
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequiresPermissions("system:quartz:pause")
	@Logs(depict = "暂停调度任务", type = GlobalsConstant.LogTypes.SYS_SCHEDULER_JOB)
	public ResultData pause(SchedulerJob job, HttpServletRequest request) {
		ResultData rd = new ResultData();
		try {
			rd.setStatus("10101");
			quartzService.pauseSchedulerJob(job);
		} catch (Exception e) {
			rd.failObjs("13102", MESSAGE_TYPE);
			logger.error(rd.getMessage() + "：", e);
		}
		return rd;
	}
	
	/**
	 * 立刻执行调度任务
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "immediately")
	@RequiresPermissions("system:quartz:immediately")
	@Logs(depict = "立刻执行调度任务", type = GlobalsConstant.LogTypes.SYS_SCHEDULER_JOB)
	public ResultData immediately(SchedulerJob job, HttpServletRequest request) {
		ResultData rd = new ResultData();
		try {
			rd.setStatus("10102");
			quartzService.immediatelyExecuteSchedulerJob(job);
		} catch (Exception e) {
			rd.failObjs("13102", MESSAGE_TYPE);
			logger.error(rd.getMessage() + "：", e);
		}
		return rd;
	}
	
	/**
	 * 恢复调度任务
	 * @param job
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "resume")
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequiresPermissions("system:quartz:resume")
	@Logs(depict = "恢复调度任务", type = GlobalsConstant.LogTypes.SYS_SCHEDULER_JOB)
	public ResultData resume(SchedulerJob job, HttpServletRequest request) {
		ResultData rd = new ResultData();
		try {
			rd.setStatus("10103");
			quartzService.resumeSchedulerJob(job);
		} catch (Exception e) {
			rd.failObjs("13102", MESSAGE_TYPE);
			logger.error(rd.getMessage() + "：", e);
		}
		return rd;
	}

}
